import utils from '../utils'
import {DataTable} from '../data'

function exportDbf(dataset, opts) {
  return dataset.layers.reduce((files, lyr) => {
    if (lyr.data) {
      files = files.concat(exportDbfFile(lyr, dataset, opts))
    }
    return files
  }, [])
}
function exportDbfFile(lyr, dataset, opts) {
  let data = lyr.data
  // create empty data table if missing a table or table is being cut out
  if (!data || opts.cut_table || opts.drop_table) {
    data = new DataTable(lyr.shapes ? lyr.shapes.length : 0)
  }
  // dbfs should have at least one column; add id field if none
  if (data.getFields().length === 0) {
    data.addIdField()
  }
  const buf = data.exportAsDbf(opts)
  if (utils.isInteger(opts.ldid)) {
    new Uint8Array(buf)[29] = opts.ldid // set language driver id
  }
  // TODO: also export .cpg page
  return [{
    content: buf,
    filename: lyr.name + '.dbf'
  }]
}

export default {
  exportDbf,
  exportDbfFile,
}